<?php
namespace App\Http\Controllers\Api\Customer;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Service\WdhService;

use App\Models\Wx\WxCustomer; //微信粉丝表

use App\Service\LockingService; //频繁操作锁定服务

use App\Service\Pay\WxPayService; //微信支付服务

use App\Models\ConfigureFunction; //配置信息

use App\Models\Customer\Customer; //会员主表

use App\Models\Customer\RechargeCard; //充值卡表

use App\Models\Customer\RechargeCardCode; //充值卡码表

use App\Models\Customer\RechargeCardFreeze; //充值卡冻结表

use App\Models\Customer\CustRechargeDetail; //会员每日充值详细表

use App\Models\Customer\CustRechargeConfirm; //会员充值审核列表

use Illuminate\Support\Facades\Redis as Redis;

use App\Models\Activity\ActivityCustomer; //会员活动表



use App\Http\Controllers\Controller;


class CustomerRechargeController extends  Controller {


    /**
     * 初始化充值接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function init( Request $request ){

        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());

        if (empty($session_id)) {
            return response()->json(['code' => 100000, 'message' => '缺少参数：session_id']);
        }

        $pcustID =  get_customer_id($session_id, $platform);

        if ( empty($pcustID) ) {
            return response()->json( ['code' => 100001, 'message' => '用户未登录'] );
        }

        $customer = Customer::select(['pcustID', 'custID', 'cardNo'])->find($pcustID);

        if ( empty($customer) ) {
            return response()->json( ['code' => 100002, 'message' => '用户不存在'] );
        }

        $is_wx_auth = 0; // 微信微信授权标识 0未授权 1已授权

        // 0订阅号 1服务号
        $wechat_type = ConfigureFunction::getConfigureField(41,'wechat_type');

        if ($platform == 0 && $wechat_type == 1) {

            $openId = redisTransformation(Redis::get($session_id . 'WECHAT_OPENID'));
            if (!$openId) {
                $weixin_array = WxCustomer::select(['uuid', 'openId'])->where(['pcustID'=> $pcustID])->get();
                if ( $weixin_array ) {
                    if (isset($weixin_array[1])) {
                        $wechat_uuid = redisTransformation(Redis::get($session_id . 'WECHAT_CUSTOMER_UUID'));
                        foreach($weixin_array as $weixin) {
                            if ($weixin['uuid'] == $wechat_uuid) {
                                $openId = $weixin['openId'];
                            }
                        }
                    } else {
                        $openId = $weixin_array[0]['openId'];
                    }
                }
            }
            if ( $openId ) {
                $is_wx_auth = 1;
            }

        }

        //查询充值有礼活动
        $recharge_prize = [];
        $recharge_activity = ActivityCustomer::getCache(32);
        if ($recharge_activity) {
            foreach ($recharge_activity as &$activity) {
                $time = Carbon::now();
                if ( $activity['start_time'] > $time || $activity['end_time'] < $time ) {
                    continue;
                }
                foreach ($activity['prize_name'] as &$prize_name) {
                    $recharge_prize[] = $prize_name;
                }
            }
        }

        $recharge_amount = []; //充值金额
        $pay_type = [];   //充值类型
        $explain = '';   //充值说明
        $adjust_amount = 0; //调整充值金额  0、不可调整  1、可调整
        $recharge_card = ''; //充值卡名称

        //会员充值设置
        $recharge_setting_data = ConfigureFunction::getConfigure(3);

        if ($recharge_setting_data) {

            if (isset($recharge_setting_data['amount'])) {
                $recharge_amount = $recharge_setting_data['amount'];
            }

            //微信支付
            if (isset($recharge_setting_data['pay_method']['weixin_pay']) && $platform == 0) {
                $pay_type[] = 1;
            }
//            //支付宝支付
//            if (isset($recharge_setting_data['pay_method']['alipay']) && $platform != 0) {
//                $pay_type[] = 2;
//            }
//            //银联支付
//            if (isset($recharge_setting_data['pay_method']['union_pay']) && $platform != 0) {
//                $pay_type[] = 3;
//            }
//            //百度钱包
//            if (isset($recharge_setting_data['pay_method']['baidu_wallet']) && $platform != 0) {
//                $pay_type[] = 4;
//            }

            if (isset($recharge_setting_data['explain']) || !empty($recharge_setting_data['explain'])) {
                $explain =  nl2br( $recharge_setting_data['explain']);
            }

            if (isset($recharge_setting_data['adjust_amount']) || !empty($recharge_setting_data['adjust_amount'])) {
                $adjust_amount = $recharge_setting_data['adjust_amount'];
            }

            //充值卡
            if ( isset($recharge_setting_data['is_recharge_card']) &&  $recharge_setting_data['is_recharge_card'] ==1 &&  $recharge_setting_data['card_name']) {
                $recharge_card = $recharge_setting_data['card_name'];
            }

        }

        //微信支付方式类型：1普通版 2代理版
        $wechat_pay_type = ConfigureFunction::getConfigureField(9,'wechat_pay_type', 1);

        /*
         * ============================
         * 查询账户余额
         * ============================
         * */

        $args_balance = [
            'openId'  => $customer['custID'],       //string，粉丝openId
            'cardNo'  => $customer['cardNo'],       //string，粉丝卡号
            'pcustID' => $customer['pcustID'],      //int，客户号
            'custID'  => $customer['custID']        //string，会员名
        ];

        $item_balance_array = WdhService::balance($args_balance);
        if ( $item_balance_array < 0 ) {
            $item_balance_array = 0;
        }

        //返回数组
        $return_array = [
            'is_wx_auth' => $is_wx_auth,
            'balance' => $item_balance_array,
            'recharge_amount' => $recharge_amount,
            'adjust_amount' => $adjust_amount,
            'recharge_card' => $recharge_card,
            'activity' => $recharge_prize,
            'pay_type' => $pay_type,
            'explain' => app_to_string($explain),
            'wechat_pay_type' => $wechat_pay_type

        ];

        return response()->json( ['code' => 200, 'message' => 'ok' , 'data' => $return_array] );

    }


    /**
     *
     * 在线充值
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function onlinePay( Request $request ){

        $platform = $request->input('platform', 6);
        $payTypeID = $request->input('pay_id'); //支付方式ID
        $online_pay_amount = $request->input('online_pay_amount'); //充值金额
        $session_id = $request->input('session_id', session_id());

        if (empty($session_id)) {
            return response()->json(['code' => 100000, 'message' => '缺少参数：session_id']);
        }

        $pcustID =  get_customer_id($session_id, $platform);

        if ( empty($pcustID) ) {
            return response()->json( ['code' => 100001, 'message' => '用户未登录'] );
        }

        $customer = Customer::select(['pcustID', 'custID', 'cardNo'])->find( $pcustID );

        if ( empty($customer) ) {
            return response()->json( ['code' => 100002, 'message' => '用户不存在'] );
        }

        if ( empty($payTypeID) ) {
            return response()->json( ['code' => 100003, 'message' => '支付方式错误'] );
        }

        if ( empty( $online_pay_amount ) ) {
            return response()->json( ['code' => 100004, 'message' => '请输入充值金额'] );
        }

        if ( !isMoney( $online_pay_amount )) {
            return response()->json( ['code' => 10005, 'message' => '请输入正确的充值金额'] );
        }

        //会员充值设置
        $recharge_configure = ConfigureFunction::getConfigure(3);

        //判断单笔订单限额
        if ( $recharge_configure['single_limit'] > 0 && $recharge_configure['single_limit'] < $online_pay_amount ) {
            return response()->json( ['code' => 100006, 'message' => '已超出单笔充值最大金额<br>最大金额：'. $recharge_configure['single_limit'] . '元' ] );
        }

        if ( $recharge_configure['daily_limit'] > 0 ) {
            //查询当天充值金额总数
            $total = CustRechargeDetail::where(['recharge_status'=>1,'pcustID' =>$customer['pcustID'], 'calDate' => date('Y-m-d')])->sum('amount');
            if ($total + $online_pay_amount > $recharge_configure['daily_limit']) {
                return response()->json( ['code' => 100007, 'message' => '已超出当日充值最大金额<br>可充值金额：'. ($recharge_configure['daily_limit'] - $total) . '元' ] );
            }
        }

        //充值id
        $recharge_id = generate_seqno('seqno_recharge_id',true) . get_random_string(3, 'number');

        //保存会员充值记录
        $this->saveRecharge($recharge_id, $customer['pcustID'], $customer['custID'], $customer['cardNo'], '', '', $online_pay_amount, 2, 0, 0, $platform);

        //加载在线支付接口文件，生成支付请求数据
        $wechat_type = ConfigureFunction::getConfigureField(41,'wechat_type');

        $trade_type = '';
        if ( $platform == 0 ) {
            if ( $wechat_type == 1 ) {
                $trade_type = 'JSAPI';
            } else {
                $trade_type = 'NATIVE';
            }
        } elseif( $platform == 6 ){
            $trade_type = 'JSAPI';
        } else {
            if ( $platform == 3 ) {
                $trade_type = 'NATIVE';
            }
        }

        $openId = redisTransformation(Redis::get($session_id . 'WECHAT_OPENID'));

        if (!$openId) {

            //小程序
            if ( $platform == 6 ) {
                $wx_applet_info = Redis::get('WX_APPLET_USER_' . $session_id);
                if (!$wx_applet_info) {
                    return response()->json(['code' => 10003, 'message' => '会员登录已失效']);
                }
                $wx_applet_info = json_decode($wx_applet_info, true);
                $openId = $wx_applet_info['openId'];
            } else {
                $weixin_array = WxCustomer::select(['uuid', 'openId'])->where(['pcustID'=> $pcustID])->get();
                if ( $weixin_array ) {
                    if (isset($weixin_array[1])) {
                        $wechat_uuid = redisTransformation(Redis::get($session_id . 'WECHAT_CUSTOMER_UUID'));
                        foreach($weixin_array as $weixin) {
                            if ($weixin['uuid'] == $wechat_uuid) {
                                $openId = $weixin['openId'];
                            }
                        }
                    } else {
                        $openId = $weixin_array[0]['openId'];
                    }
                }
            }

        }

        //微信异步接收路径
        $notify_url = $request->getSchemeAndHttpHost() . '/onlinepay/weixin/notify';

        $params = [
            'out_trade_no' => $recharge_id,
            'trade_type' => $trade_type,
            'payTypeID' => $payTypeID,
            'mallID' => 0,
            'body' => '微商城',
            'total_fee' => $online_pay_amount,
            'pcustID' => $customer['pcustID'],
            'type' => 3,
            'openId' => $openId,
            'notify_url' => $notify_url
        ];

        $WxPayService = new WxPayService($params);

        $wx_pay = $WxPayService->request();
        if ($wx_pay['code'] != 200) {
            return response()->json(['code' => $wx_pay['code'], 'message' => $wx_pay['message']]);
        }

        $wx_pay['data']['recharge_id'] = $recharge_id;

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $wx_pay['data']]);

    }



    /**
     *
     * 充值卡充值初始化
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function rechargeCardInit( Request $request ){

        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());

        if (empty($session_id)) {
            return response()->json(['code' => 100000, 'message' => '缺少参数：session_id']);
        }

        $pcustID =  get_customer_id($session_id, $platform);

        if ( empty($pcustID) ) {
            return response()->json( ['code' => 100001, 'message' => '用户未登录'] );
        }

        $customer = Customer::select(['pcustID', 'custID', 'cardNo'])->find( $pcustID );

        if ( empty($customer) ) {
            return response()->json( ['code' => 100002, 'message' => '用户不存在'] );
        }

        //会员充值设置
        $recharge_configure = ConfigureFunction::getConfigure(3);

        $is_full_pay = 1;   //1、全额充值  2部分充值

        if ( isset($recharge_configure['is_recharge_card'])&& !empty($recharge_configure['is_recharge_card'])) {
            if ( isset($recharge_configure['is_full_pay']) && $recharge_configure['is_full_pay'] == 2) {
                $is_full_pay = 2;
            }
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => [ 'is_full_pay' => $is_full_pay] ]);

    }


    /**
     *
     * 查询线下充值卡信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchOfflineRechargeCard( Request $request ){


        //获取参数
        $pwd = $request-> input('card_pwd');
        $cardNo = $request-> input('card_code');
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());

        if ( empty( $cardNo ) ) {
            return response()->json( ['code' => 100000, 'message' => '卡号不能为空'] );
        }
        if ( empty( $pwd ) ) {
            return response()->json( ['code' => 100001, 'message' => '密码不能为空'] );
        }
        if (empty($session_id)) {
            return response()->json(['code' => 100002, 'message' => '缺少参数：session_id']);
        }

        $pcustID =  get_customer_id($session_id, $platform);

        if ( empty($pcustID) ) {
            return response()->json( ['code' => 100003, 'message' => '用户未登录'] );
        }

        $index = 'WDH_RECHARGE_CARD_LOCK_' . $pcustID . '_' . $cardNo;
        $error_num = 0;
        if ( Redis::exists($index) ) {
            $error_num = Redis::get($index);
        }

        if ( $error_num >= 3 ) {
            return response()->json(['code' => 100105, 'message' => '对不起，您操作错误次数过多，该卡被冻结了，解冻请联系客服。']);
        }

        //查询用户冻结信息
        $freeze_res = RechargeCardFreeze::select(['id'])->where(['pcustID' => $pcustID, 'card_no' => $cardNo])->first();
        if ( !empty($freeze_res) ) {
            return response()->json( ['code' => 100105, 'message' => '对不起，您的充值卡已经被冻结，解冻请联系客服。'] );
        }

        //检查用户信息
        $customer = Customer::select(['pcustID', 'custID', 'cardNo'])->find( $pcustID );
        if ( empty($customer) ) {
            return response()->json( ['code' => 100006, 'message' => '用户不存在'] );
        }

        //查询线下充值卡信息
        $recharge_array = [
            'cardNo' => $cardNo,
            'pwd' => $pwd
        ];

        $recharge_res = WdhService::validateQuery( $recharge_array );
        if ( $recharge_res['code'] != 200 ) {
            $error_num++;
            Redis::setex( $index, 7200, $error_num);
            //记录充值卡冻结
            if ( $error_num >= 3) {
                $this->saveRechargeCardFreeze($customer['pcustID'], $customer['custID'], $cardNo, 0 );
            }

            return response()->json( ['code' => 100106, 'message' => $recharge_res['message'],'data'=>['input_pwd_num' => 3 - $error_num]] );
        }

        return response()->json( ['code' => 200, 'message' => 'ok', 'data'=>['balance' => $recharge_res['data']]] );

    }


    /**
     *
     * 充值卡充值
     * @param Request $request
     * array (
     *   'online_pay_amount'=>100            充值金额
     *   'pay_id'=>10                                       支付方式ID
     * )
     * @return \Illuminate\Http\JsonResponse
     */
    public function cardPay( Request $request ){

        $pwd = $request-> input('card_pwd');
        $cardNo = $request-> input('card_code');
        $platform = $request-> input('platform', 6);
        $amount = $request-> input('card_amount','');
        $session_id = $request->input('session_id', session_id());

        if ( empty( $pwd ) ) {
            return response()->json( ['code' => 100000, 'message' => '密码不能为空'] );
        }
        if ( empty( $cardNo ) ) {
            return response()->json( ['code' => 100001, 'message' => '卡号不能为空'] );
        }

        if (empty($session_id)) {
            return response()->json(['code' => 100002, 'message' => '缺少参数：session_id']);
        }

        $pcustID =  get_customer_id($session_id, $platform);

        if ( empty($pcustID) ) {
            return response()->json( ['code' => 100003, 'message' => '用户未登录'] );
        }

        //加锁redis 防止同时使用一张充值卡
        $redis_index = 'WDH_RECHARGE_CARD_CUST_LOCK_' . $cardNo . '_' . $pwd ;
        if ( LockingService::check( $redis_index ) ) {
            return response()->json(['code' => 100004 , 'message' => '请求频繁']);
        }

        //检查用户输入密码错误次数
        $index = 'WDH_RECHARGE_CARD_LOCK_' . $pcustID . '_' . $cardNo;
        $error_num = 0; //已经输错的次数
        if ( Redis::exists($index) ) {
            $error_num = Redis::get($index);
        }

        if ( $error_num >= 3 ) {
            LockingService::remove();
            return response()->json(['code' => 100105, 'message' => '对不起，您操作错误次数过多，该卡被冻结了，解冻请联系客服']);
        }


        //查询用户信息
        $customer = Customer::select(['pcustID', 'custID', 'cardNo'])->find( $pcustID );
        if ( empty($customer) ) {
            LockingService::remove();
            return response()->json( ['code' => 100006, 'message' => '用户不存在'] );
        }

        //查询用户冻结信息
        $freeze_res = RechargeCardFreeze::select(['id'])->where(['pcustID'=>$customer['pcustID'], 'card_no'=>$cardNo])->first();
        if ( !empty($freeze_res) ) {
            LockingService::remove();
            return response()->json( ['code' => 100105, 'message' => '对不起，你的充值卡已经被冻结，解冻请联系客服。'] );
        }

        //会员充值设置
        $recharge_configure = ConfigureFunction::getConfigure(3);

        //充值卡的类别 1、线上充值卡 2 线下充值卡
        $card_type = 1;

        if ( isset($recharge_configure['is_recharge_card'])&& empty($recharge_configure['is_recharge_card'])) {
            $card_type = $recharge_configure['consume_type'];
        }

        //充值id
        $recharge_id = generate_seqno('seqno_recharge_id',true) . get_random_string(3, 'number');

        if ( $card_type == 1 ) {

            $recharge_card_code_res = RechargeCardCode::select(['card_id', 'card_no', 'code_status', 'card_amount'])->where(['card_no'=>$cardNo])->first();

            if ( empty($recharge_card_code_res) ) {
                LockingService::remove();
                return response()->json( ['code' => 100107, 'message' => '请输入正确的卡号'] );
            }

            $recharge_card_code = RechargeCardCode::select(['card_id', 'card_no', 'code_status', 'card_amount'])->where(['card_no'=>$cardNo,'card_pwd' => $pwd])->first();

            if ( empty($recharge_card_code) ) {
                $error_num++;
                Redis::setex( $index, 7200, $error_num);
                //记录充值卡冻结
                if ( $error_num >= 3) {
                    $this->saveRechargeCardFreeze($customer['pcustID'], $customer['custID'], $cardNo, $recharge_card_code_res['card_amount'] );
                }
                LockingService::remove();
                return response()->json( ['code' => 100106, 'message' => '密码错误', 'data'=>['input_pwd_num' => 3 - $error_num]] );
            }

            //判断有效期
            $recharge_card = RechargeCard::select(['validity', 'start_time', 'end_time'])->where(['id'=>$recharge_card_code['card_id']])->first();
            if ( !empty($recharge_card) && $recharge_card['validity'] !=1 ) {
                if ( Carbon::now() > $recharge_card['end_time'] || Carbon::now() < $recharge_card['start_time'] ) {
                    LockingService::remove();
                    return response()->json( ['code' => 100010, 'message' => '该卡不在有效期限内'] );
                }
            }

            if ( $recharge_card_code['code_status'] == 1 ) {
                LockingService::remove();
                return response()->json( ['code' => 100011, 'message' => '该充值卡未激活'] );
            }

            if ( $recharge_card_code['code_status'] == 3 ) {
                LockingService::remove();
                return response()->json( ['code' => 100012, 'message' => '该充值卡已失效'] );
            }

            if ( $recharge_card_code['code_status'] == 4 ) {
                LockingService::remove();
                return response()->json( ['code' => 100013, 'message' => '该卡号已经绑定'] );
            }

            if ( $recharge_card_code['code_status'] == 5 ) {
                LockingService::remove();
                return response()->json( ['code' => 100014, 'message' => '该充值卡已冻结'] );
            }

            if ( $recharge_card_code['card_amount'] < $amount) {
                LockingService::remove();
                return response()->json( ['code' => 100015, 'message' => '该充值卡最大额度是' . $recharge_card_code['card_amount'] . '元'] );
            }

            $amount = $recharge_card_code['card_amount'];

            $recharge_array = [
                'pcustID' => $customer['pcustID'],
                'custID' => $customer['custID'],
                'cardNo' => $customer['cardNo'],
                'amount' => $amount,
                'remark' => '充值卡充值'
            ];

            $recharge_res = WdhService::recharge( $recharge_array );

            if ( $recharge_res['code'] == 200 ) {
                //充值成功改变充值卡状态 已使用
                RechargeCardCode::where(['card_no'=>$cardNo,'card_pwd'=> $pwd ])->update(['pcustID'=>$customer['pcustID'], 'custID'=>$customer['custID'], 'used_time'=> Carbon::now(), 'code_status' => 4]);
            }

        } else {

            //查询线下充值卡信息
            $recharge_array = [
                'cardNo' => $cardNo,
                'pwd' => $pwd
            ];

            $recharge_res = WdhService::validateQuery( $recharge_array );
            if ( $recharge_res['code'] != 200 ) {
                $error_num++;
                Redis::setex( $index, 7200, $error_num);
                //记录充值卡冻结
                if ( $error_num >= 3) {
                    $this->saveRechargeCardFreeze($customer['pcustID'], $customer['custID'], $cardNo, 0 );
                }
                LockingService::remove();
                return response()->json( ['code' => $recharge_res['code'], 'message' => $recharge_res['message'],'data'=>['input_pwd_num' => 3 - $error_num]] );
            }

            if ( !$amount ) {
                $amount = $recharge_res['data'];
            } elseif ( $amount > $recharge_res['data'] ){
                LockingService::remove();
                return response()->json( ['code' => 100016, 'message' => '该充值卡最大额度是' . $recharge_res['data'] . '元'] );
            }

            //线下账户充值
            $recharge_array = [
                'transferInAccountCode' => $customer['cardNo'],
                'transferInAccountType' => 0,
                'transferOutAccountCode' => $cardNo,
                'transferOutAccountType' => 0,
                'transferOutPwd' => $pwd,
                'transferOutAmount' => $amount,
                'tranId' => $recharge_id,
                'tranTime' => Carbon::now()
            ];

            $recharge_res = WdhService::transfer( $recharge_array );

        }

        if ( $recharge_res['code'] != 200 ) {
            LockingService::remove();
            return response()->json( ['code' => $recharge_res['code'], 'message' => $recharge_res['message']] );
        }

        $remark = '充值卡充值';
        if ( $card_type == 1 ) {
            $remark = '线下充值卡充值';
        }


        //保存会员充值记录
        $this->saveRecharge($recharge_id, $customer['pcustID'], $customer['custID'], $customer['cardNo'], '', '', $amount, 1, 1, 1, 1, $remark);

        //删除输入密码次数
        if ( Redis::exists($index) ) {
            Redis::del($index);
        }

        LockingService::remove();
        return response()->json( ['code' => 200, 'message' => '充值成功'] );

    }


    /**
     * 充值记录
     * @param Request $request
     * @return array
     */

    public function rechargeLog( Request $request ) {

        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $limit = $request->input('limit');
        $page = $request->input('page');

        if ( empty( $session_id ) ) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
        }

        if (!ebsig_is_int($limit)) {
            $limit = 10;
        }

        if (!ebsig_is_int($page)) {
            $page = 1;
        }

        $pcustID = get_customer_id($session_id, $platform);

        if ( !$pcustID ) {
            return response()->json( ['code' => 100001, 'message' => '用户未登录'] );
        }

        $recharge_data = CustRechargeDetail::where(['pcustID' => $pcustID ])->orderBy('createTime', 'DESC')->paginate($limit)->toArray();
        if ( !$recharge_data ) {
            return response()->json([ 'code' => 100002, 'message' => '没有相关数据' ]);
        }

        $return_array = [];

        foreach ( $recharge_data['data'] as $recharge ) {

            $return_array[] = [
                'source' => $recharge['source'],
                'amount' => $recharge['amount'],
                'createTime' => $recharge['createTime'],
                'recharge_status' => $recharge['recharge_status'],
                'api_sync_status' => $recharge['api_sync_status'],
                'remark' => $recharge['remark']
            ];

        }

        return response()->json([
            'code' => 200 ,
            'message' => 'ok',
            'data' => [
                'count' => $recharge_data['total'],
                'list' => $return_array
            ]
        ]);

    }



    /**
     * 保存会员充值记录
     * @param int $tranId 充值id
     * @param int $pcustID 会员号
     * @param string $custID 会员号
     * @param string $card_no 第三方会员卡号
     * @param string $recharge_card_no 充值卡卡号
     * @param string $recharge_card_pwd 充值卡卡密
     * @param double $amount 充值金额
     * @param int $source 充值来源:1.充值卡 2.微信 3.支付宝
     * @param int $recharge_status 充值状态：0、未充值 1、已充值
     * @param int $api_sync_status 接口同步状态：1、已同步 0、未同步
     * @param int $platform 平台类型
     * @param string $remark 备注
     * @return bool
     */
    public function saveRecharge( $tranId, $pcustID, $custID, $card_no, $recharge_card_no='', $recharge_card_pwd='', $amount, $source, $recharge_status = 1, $api_sync_status = 1 , $platform = 0, $remark ='') {

        //记录会员每日充值成功后详细表
        $cust_recharge_detail = new CustRechargeDetail();
        $cust_recharge_detail->uuid = makeUuid();
        $cust_recharge_detail->timeStamp = Carbon::now();
        $cust_recharge_detail->creator = $custID;
        $cust_recharge_detail->createTime = Carbon::now();
        $cust_recharge_detail->recharge_id = $tranId;
        $cust_recharge_detail->pcustID = $pcustID;
        $cust_recharge_detail->custID = $custID;
        $cust_recharge_detail->card_no = $card_no;
        $cust_recharge_detail->recharge_card_no = $recharge_card_no;
        $cust_recharge_detail->recharge_card_pwd = $recharge_card_pwd ? $recharge_card_pwd : '';
        $cust_recharge_detail->source = $source;
        $cust_recharge_detail->amount = $amount;
        $cust_recharge_detail->calDate = date('Y-m-d');
        $cust_recharge_detail->recharge_status = $recharge_status;
        $cust_recharge_detail->api_sync_status = $api_sync_status;
        $cust_recharge_detail->platform = $platform;
        $cust_recharge_detail->remark = $remark;
        $cust_recharge_detail->save();

        return true;

    }


    /**
     * 保存待审核的充值信息
     * @param int $pcustID
     * @param string $cardNo 会员卡号
     * @param array $args 充值数据
     * @return bool
     */
    public function saveRechargeConfirm( $pcustID, $cardNo, $args ) {

        //会员每日充值最后一次的金额超过单日限制金额将记录添加到会员充值审核列表
        $cust_recharge_confirm = new CustRechargeConfirm();
        $cust_recharge_confirm->uuid = makeUuid();
        $cust_recharge_confirm->timeStamp = Carbon::now();
        $cust_recharge_confirm->creator = 'system';
        $cust_recharge_confirm->createTime = Carbon::now();
        $cust_recharge_confirm->pcustID = $pcustID;
        $cust_recharge_confirm->transferInAccountCode = $cardNo;
        $cust_recharge_confirm->transferOutAccountCode = $args['transferOutAccountCode'];
        $cust_recharge_confirm->transferOutPwd = '';
        $cust_recharge_confirm->transferOutAmount = $args['transferOutAmount'];
        $cust_recharge_confirm->recharge_status = 1;
        $cust_recharge_confirm->save( );

        return true;

    }


    /**
     * 保存充值卡冻结信息
     * @param int $pcustID
     * @param string $custID 会员名
     * @param string $cardNo 会员卡号
     * @return bool
     */
    public function saveRechargeCardFreeze( $pcustID, $custID, $cardNo, $cardAmount ) {

        $freeze_res = RechargeCardFreeze::select(['id'])->where(['pcustID'=>$pcustID, 'card_no'=>$cardNo])->first();

        if ( empty($freeze_res) ) {
            $recharge_card_freeze = new RechargeCardFreeze();
            $recharge_card_freeze->uuid = makeUuid();
            $recharge_card_freeze->timeStamp = Carbon::now();
            $recharge_card_freeze->creator = 'system';
            $recharge_card_freeze->createTime = Carbon::now();
            $recharge_card_freeze->pcustID = $pcustID;
            $recharge_card_freeze->custID = $custID;
            $recharge_card_freeze->card_no = $cardNo;
            $recharge_card_freeze->card_amount = $cardAmount ? $cardAmount: 0;
            $recharge_card_freeze->save( );
        }

        return true;

    }



}